<template>
  <div class="admin-add-pet">
    <div class="container">
      <div class="back-link mb-3">
        <router-link to="/admin/pets">
          <i class="el-icon-arrow-left"></i> 返回宠物列表
        </router-link>
      </div>
      
      <h1 class="page-title">添加宠物</h1>
      
      <el-card class="pet-form-card" v-loading="loading">
        <el-form 
          ref="petForm" 
          :model="petData" 
          :rules="rules" 
          label-position="top"
          @submit.prevent="submitForm"
        >
          <el-row :gutter="20">
            <el-col :md="12" :sm="24">
              <el-form-item label="宠物名称" prop="name">
                <el-input v-model="petData.name" placeholder="请输入宠物名称" />
              </el-form-item>
            </el-col>
            
            <el-col :md="12" :sm="24">
              <el-form-item label="类别" prop="category_id">
                <el-select v-model="petData.category_id" placeholder="请选择宠物类别" style="width: 100%">
                  <el-option 
                    v-for="category in categories" 
                    :key="category.id" 
                    :label="category.name" 
                    :value="category.id" 
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="petData.gender" placeholder="请选择性别" style="width: 100%">
                  <el-option label="公" value="male" />
                  <el-option label="母" value="female" />
                  <el-option label="未知" value="unknown" />
                </el-select>
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="年龄" prop="age">
                <el-input-number v-model="petData.age" :precision="1" :step="0.5" :min="0" :max="30" style="width: 100%" />
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="品种" prop="breed">
                <el-input v-model="petData.breed" placeholder="请输入品种" />
              </el-form-item>
            </el-col>
            
            <el-col :md="6" :sm="12" :xs="24">
              <el-form-item label="体型" prop="size">
                <el-select v-model="petData.size" placeholder="请选择体型" style="width: 100%">
                  <el-option label="小型" value="small" />
                  <el-option label="中型" value="medium" />
                  <el-option label="大型" value="large" />
                  <el-option label="超大型" value="extra large" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="是否已被领养">
                <el-switch v-model="petData.is_adopted" :active-value="1" :inactive-value="0" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="描述" prop="description">
            <el-input 
              type="textarea" 
              v-model="petData.description" 
              placeholder="请输入宠物的详细介绍" 
              :rows="5" 
            />
          </el-form-item>
          
          <el-form-item label="健康状况" prop="health_status">
            <el-input 
              type="textarea" 
              v-model="petData.health_status" 
              placeholder="请输入宠物的健康状况" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="行为习性" prop="behavior">
            <el-input 
              type="textarea" 
              v-model="petData.behavior" 
              placeholder="请输入宠物的行为习性" 
              :rows="3" 
            />
          </el-form-item>
          
          <el-form-item label="宠物照片" prop="image">
            <div class="pet-image-uploader">
              <!-- Element Plus上传组件 -->
              <el-upload
                class="pet-image-uploader-el"
                action="#"
                :auto-upload="true"
                :http-request="uploadImage"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                drag
                accept="image/jpeg,image/png"
              >
                <template #default>
                  <div v-if="imageUrl" class="image-preview">
                    <img :src="imageUrl" class="pet-image" :alt="petData.name || '宠物图片'" />
                    <div class="image-overlay">
                      <i class="el-icon-refresh"></i>
                      <div>点击更换图片</div>
                    </div>
                  </div>
                  <div v-else class="upload-placeholder">
                    <i class="el-icon-upload"></i>
                    <div class="upload-text">点击此处或拖拽图片上传</div>
                    <div class="el-upload__tip">请上传宠物照片，只能上传 jpg/png 文件，且不超过 5MB</div>
                  </div>
                </template>
              </el-upload>
              
              <!-- 隐藏原生上传输入框 -->
              <input 
                type="file" 
                id="pet-image-native" 
                accept="image/jpeg,image/png" 
                @change="handleNativeUpload" 
                style="display: none;" 
              />
              
              <div class="upload-controls">
                <el-button v-if="imageUrl" type="danger" size="small" @click="removeImage" class="control-btn">
                  <i class="el-icon-delete"></i> 删除图片
                </el-button>
                <el-button v-else type="primary" size="small" @click="triggerNativeFileDialog" class="control-btn">
                  <i class="el-icon-folder-opened"></i> 浏览本地图片
                </el-button>
              </div>
            </div>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm" :loading="submitting">添加宠物</el-button>
            <el-button @click="$router.push('/admin/pets')">取消</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useStore } from 'vuex';
import axios from 'axios';
import { readLocalImage } from '@/utils/image';

export default {
  name: 'AdminAddPet',
  setup() {
    const store = useStore();
    const router = useRouter();
    const petForm = ref(null);
    const loading = ref(false);
    const submitting = ref(false);
    const imageUrl = ref('');
    const imageFile = ref(null);
    
    const API_URL = '/api';
    
    // 表单数据
    const petData = reactive({
      name: '',
      category_id: '',
      breed: '',
      age: 0,
      gender: 'unknown',
      size: 'medium',
      description: '',
      health_status: '',
      behavior: '',
      is_adopted: 0,
      image_url: ''
    });
    
    // 分类数据
    const categories = ref([]);
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入宠物名称', trigger: 'blur' },
        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      category_id: [
        { required: true, message: '请选择宠物类别', trigger: 'change' }
      ],
      gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
      ],
      size: [
        { required: true, message: '请选择体型', trigger: 'change' }
      ],
      age: [
        { required: true, message: '请输入宠物年龄', trigger: 'blur' }
      ]
    };
    
    // 获取认证头
    const getAuthHeaders = () => {
      const token = store.getters['auth/token'];
      if (!token) {
        throw new Error('未找到认证令牌，请重新登录');
      }
      
      return {
        'Authorization': `Bearer ${token}`,
        'x-auth-token': token,
        'Content-Type': 'multipart/form-data'
      };
    };
    
    // 加载分类数据
    const loadCategories = async () => {
      loading.value = true;
      try {
        const token = store.getters['auth/token'];
        if (!token) {
          ElMessage.error('未登录或会话已过期，请重新登录');
          router.push('/login');
          return;
        }
        
        const response = await axios.get(`${API_URL}/pets/categories`, {
          headers: {
            'Authorization': `Bearer ${token}`,
            'x-auth-token': token
          }
        });
        categories.value = response.data;
      } catch (error) {
        ElMessage.error('加载分类数据失败');
        console.error(error);
      } finally {
        loading.value = false;
      }
    };
    
    // 图片上传前的验证
    const beforeImageUpload = (file) => {
      console.log('上传前验证文件:', file); // 调试日志
      
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传宠物图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      
      if (!isLt5M) {
        ElMessage.error('上传宠物图片大小不能超过 5MB!');
        return false;
      }
      
      console.log('文件验证通过'); // 调试日志
      return true;
    };
    
    // 自定义上传图片方法
    const uploadImage = async (options) => {
      const file = options.file;
      console.log('开始上传图片:', file.name, file.type, `${(file.size / 1024 / 1024).toFixed(2)}MB`);
      
      // 验证文件类型和大小
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传宠物图片只能是 JPG 或 PNG 格式!');
        return;
      }
      
      if (!isLt5M) {
        ElMessage.error('上传宠物图片大小不能超过 5MB!');
        return;
      }
      
      // 保存文件引用，用于后续表单提交
      imageFile.value = file;
      
      // 使用工具函数预览图片
      try {
        imageUrl.value = await readLocalImage(file);
        console.log('图片预览已加载');
        
        // 触发回调以通知上传成功
        if (options.onSuccess) {
          options.onSuccess();
        }
      } catch (error) {
        console.error('处理图片时发生错误:', error);
        ElMessage.error('处理图片时发生错误，请重试');
        if (options.onError) {
          options.onError(error);
        }
      }
    };
    
    // 提交表单
    const submitForm = async () => {
      if (!petForm.value) return;
      
      try {
        // 验证表单
        await petForm.value.validate();
        
        // 验证图片是否已上传
        if (!imageFile.value) {
          ElMessage.warning('请上传宠物照片');
          return;
        }
        
        // 检查登录状态和获取token
        const token = store.getters['auth/token'];
        if (!token) {
          ElMessage.error('未登录或会话已过期，请重新登录');
          router.push('/login');
          return;
        }
        
        submitting.value = true;
        console.log('准备提交表单数据，图片文件:', imageFile.value ? {
          name: imageFile.value.name,
          type: imageFile.value.type,
          size: `${(imageFile.value.size / 1024 / 1024).toFixed(2)}MB`
        } : 'no file');
        
        // 创建表单数据
        const formData = new FormData();
        formData.append('image', imageFile.value);
        
        // 确保数值类型正确
        const petDataToSubmit = {
          ...petData,
          age: Number(petData.age) || 0,
          category_id: Number(petData.category_id) || null
        };
        
        // 添加所有字段到表单数据
        Object.keys(petDataToSubmit).forEach(key => {
          if (petDataToSubmit[key] !== undefined && petDataToSubmit[key] !== null) {
            formData.append(key, petDataToSubmit[key]);
            console.log(`添加表单字段: ${key} =`, petDataToSubmit[key]);
          }
        });
        
        console.log('提交的宠物数据:', petDataToSubmit);
        
        // 设置请求头
        const headers = {
          'Authorization': `Bearer ${token}`,
          'x-auth-token': token,
          // 重要: 使用FormData时不要手动设置Content-Type
        };
        
        console.log('开始发送请求...');
        // 发送请求
        const response = await axios.post(`${API_URL}/pets`, formData, { headers });
        
        console.log('服务器响应:', response.data);
        
        if (response.data) {
          ElMessage.success('宠物添加成功');
          router.push('/admin/pets');
        } else {
          throw new Error('服务器返回无效数据');
        }
      } catch (error) {
        console.error('添加宠物失败:', error);
        
        // 处理特定错误
        if (error.response) {
          console.error('错误响应:', error.response.status, error.response.data);
          if (error.response.status === 401) {
            ElMessage.error('认证失败，请重新登录');
            router.push('/login');
          } else if (error.response.status === 413) {
            ElMessage.error('上传文件过大，请选择小于5MB的图片');
          } else if (error.response.data && error.response.data.message) {
            ElMessage.error(`添加失败: ${error.response.data.message}`);
          } else {
            ElMessage.error(`添加失败: ${error.message}`);
          }
        } else {
          ElMessage.error(`添加失败: ${error.message}`);
        }
      } finally {
        submitting.value = false;
      }
    };
    
    // 移除已上传的图片
    const removeImage = () => {
      imageFile.value = null;
      imageUrl.value = '';
    };
    
    // 触发原生文件对话框
    const triggerNativeFileDialog = () => {
      document.getElementById('pet-image-native').click();
    };
    
    // 处理原生文件上传
    const handleNativeUpload = async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      
      console.log('原生文件上传:', file.name, file.type, `${(file.size / 1024 / 1024).toFixed(2)}MB`);
      
      // 验证文件类型和大小
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;
      
      if (!isJPG && !isPNG) {
        ElMessage.error('上传宠物图片只能是 JPG 或 PNG 格式!');
        return;
      }
      
      if (!isLt5M) {
        ElMessage.error('上传宠物图片大小不能超过 5MB!');
        return;
      }
      
      // 保存文件引用
      imageFile.value = file;
      
      // 使用工具函数预览图片
      try {
        imageUrl.value = await readLocalImage(file);
        console.log('原生上传图片预览已加载');
      } catch (error) {
        console.error('处理图片时发生错误:', error);
        ElMessage.error('处理图片时发生错误，请重试');
      }
      
      // 重置文件输入，以便再次选择同一文件
      event.target.value = '';
    };
    
    // 组件挂载时加载数据
    onMounted(() => {
      loadCategories();
    });
    
    return {
      petForm,
      petData,
      categories,
      rules,
      loading,
      submitting,
      imageUrl,
      imageFile,
      beforeImageUpload,
      uploadImage,
      submitForm,
      removeImage,
      triggerNativeFileDialog,
      handleNativeUpload
    };
  }
}
</script>

<style lang="scss" scoped>
@use "sass:color";

.admin-add-pet {
  min-height: calc(100vh - 200px);
  padding: 40px 0;
}

.back-link {
  margin-bottom: 20px;
  
  a {
    color: var(--primary-color);
    display: inline-flex;
    align-items: center;
    
    i {
      margin-right: 5px;
    }
    
    &:hover {
      color: color.adjust(#42b983, $lightness: -10%);
    }
  }
}

.pet-form-card {
  margin-bottom: 40px;
}

.pet-image-uploader {
  margin-bottom: 20px;
  
  .image-preview {
    width: 100%;
    height: 100%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 6px;
    overflow: hidden;
    
    .pet-image {
      max-width: 100%;
      height: auto;
      max-height: 300px;
      display: block;
      margin: 0 auto;
      border-radius: 4px;
      object-fit: contain;
      transition: transform 0.3s ease, filter 0.3s ease;
    }
    
    .image-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: rgba(0, 0, 0, 0.6);
      color: white;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      opacity: 0;
      transition: opacity 0.3s ease;
      
      i {
        font-size: 32px;
        margin-bottom: 10px;
      }
    }
    
    &:hover {
      .pet-image {
        transform: scale(1.05);
        filter: blur(2px);
      }
      
      .image-overlay {
        opacity: 1;
      }
    }
  }
  
  :deep(.el-upload-dragger) {
    width: 100%;
    height: auto;
    min-height: 220px;
    padding: 20px;
    background-color: #f5f7fa;
    border: 2px dashed #c0c4cc;
    border-radius: 6px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: all 0.3s ease;
    
    &:hover {
      border-color: var(--primary-color);
      background-color: rgba(32, 160, 255, 0.06);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
    
    &.is-dragover {
      background-color: rgba(32, 160, 255, 0.1);
      border-color: var(--primary-color);
      transform: scale(1.02);
    }
  }
  
  .upload-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 100%;
    padding: 20px;
    
    i {
      font-size: 48px;
      color: #909399;
      margin-bottom: 16px;
      transition: color 0.3s ease, transform 0.3s ease;
    }
    
    &:hover i {
      color: var(--primary-color);
      transform: scale(1.1);
    }
  }
  
  .upload-text {
    font-size: 16px;
    color: #606266;
    margin-bottom: 8px;
    font-weight: 500;
  }
  
  :deep(.el-upload__tip) {
    text-align: center;
    margin-top: 8px;
    color: #909399;
  }
  
  .upload-controls {
    display: flex;
    justify-content: center;
    margin-top: 10px;
    
    .control-btn {
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
  }
}

.preview-controls {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.mb-3 {
  margin-bottom: 15px;
}

@media (max-width: 768px) {
  .pet-image-uploader {
    .pet-image-uploader-icon,
    .pet-image {
      width: 100%;
    }
  }
}
</style> 